package cn.enjoy.socket.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.UUID;

/**
 * @author K
 * @date 2024-06-04 20:35
 * 文件上传服务端（先启动）
 **/
public class TCPUploadFileService {
    public static void main(String[] args) {
        try {
            //创建服务端的Socket，并监听指定端口
            ServerSocket serverSocket = new ServerSocket(10086);
            //监听指定端口（等待数据的发来）
            Socket socket = serverSocket.accept();

            //从Socket里获取网络输入流(这个流有用户传来的数据信息)
            BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());

            //获取服务器的输出流，用来写到服务器的资源文件夹下
            //获取资源路径（后面用来存储文件的）
            URL url = TCPUploadFileClient.class.getResource("/file");
            assert url != null; //断言明确肯定url不为null
            String fileName = UUID.randomUUID() + ".zip";
            FileOutputStream fileOutputStream = new FileOutputStream(url.getFile() + "/" + fileName);
            //包装一层缓冲流
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            //写入资源到服务器资源下
            byte[] bytes = new byte[1024];
            int index = 0;
            while ((index = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, index);
            }
            //告知服务端接收文件成功（写出文件信息）（其实下载也是一个样子，只不过是流的信息是颠倒的）
            socket.shutdownInput();
            //写出成功信息
            BufferedWriter bufferedWriter =
                    new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("文件上传成功，上传位置：" + url.getFile() + "/" + fileName);
            bufferedWriter.flush();
            bufferedWriter.newLine();
            bufferedWriter.close();

            //关闭Socket还得关闭我们自己创建的流
            socket.close();
            bufferedOutputStream.close();
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}